package com.srdl.synchronizedTest;

import com.utils.common.ResponseEnum;
import com.utils.common.ServerResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping(value="/synchronizedTestController")
public class SynchronizedTestController {


    private static Logger logger = LoggerFactory.getLogger(SynchronizedTestController.class);

    @Autowired
    private SynchronizedByKey synchronizedByKey;

    private Map<String,String> map = new HashMap<>();

    @GetMapping(value="/test1/{orderId}")
    public ServerResponse list(@PathVariable("orderId") String orderId) throws InterruptedException {

        synchronizedByKey.exec(orderId,() -> {
            logger.info("[{}] 开始",orderId);
            try {
                service(orderId);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.info("[{}] 结束",orderId);
        });
        return ServerResponse.getInstance().responseEnum(ResponseEnum.UPDATE_SUCCESS);
    }


    public void service(String orderId) throws InterruptedException {
        logger.info(map.toString());
        Thread.sleep(2000);
        if (map.get(orderId) != null){
            logger.info("[{}] 接单",orderId);
            map.remove(orderId);
            logger.info("[{}] 完成",orderId);
        }else{
            logger.info("[{}] 已经被接走",orderId);
        }
        logger.info(map.toString());
    }

    @GetMapping(value="/init")
    public void init(){
        map = new HashMap<>();
        for (int i = 0; i < 10; i++) {
            map.put("00"+i,""+i);
        }
    }
}
